<template>
  <basic-dialog
    title="关联弹框"
    width="65%"
    :visible="dialogVisible"
    :show-close="false"
    :showFooter="false"
  >
    <table-form
      ref="tableForm"
      :formItemList="formItemList"
      :allDisabled="isAllDisabled"
      :showBasicAction="!isAllDisabled"
      @getFormData="getFormDataFunc"
    >
      <template slot="extensionActions">
        <template v-if="tabs.current === tabs.nameList[0]">
          <el-button type="primary" @click="handleBatchAssociated">批量关联</el-button>
          <el-button type="primary" @click="handleAllAssociated">全部关联</el-button>
        </template>
        <template v-else>
          <el-button @click="handleBatchCancel">批量取消</el-button>
        </template>
        <el-button @click="handleReturnDetails">返回详情</el-button>
      </template>
    </table-form>
    <el-tabs
      v-model="tabs.current"
      @tab-click="handleSwitchTabs"
      style="margin: 10px"
    >
      <el-tab-pane
        label="筛选结果"
        :name="tabs.nameList[0]"
      >
      </el-tab-pane>
      <el-tab-pane
        label="已关联"
        :name="tabs.nameList[1]"
      >
      </el-tab-pane>
    </el-tabs>
    <skus-table
      showSelectCol
      showPagination
      :columns="tableInfo.columns"
      :loading="tableInfo.loading"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :total="pagination.total"
      :selectionChange="handleSelectionChange"
      :checkSelectable="checkSelectableFunc"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
  </basic-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import TableForm from './TableForm';
import SkusTable from '@/components/skusTable';
import { formItemList, tableColumns } from '../constants/associatedDialog';
import { isResponseSuccess } from '@/utils/bizUtils';
export default {
  props: {
    batchNo: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    BasicDialog,
    TableForm,
    SkusTable
  },
  data () {
    return {
      dialogVisible: false,
      formItemList: formItemList,
      tabs: {
        current: 'firstTab', // 当前tabs页签
        nameList: ['firstTab', 'secondTab'] // tabs页签key集合
      },
      isAllDisabled: false, // 是否需要全部禁用状态， 已关联不可操作表单
      tableInfo: {
        list: [],
        columns: tableColumns,
        loading: false
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 50, // 每页条数
        total: 0
      },
      firstStoreData: { // 筛选结果数据备份
        /**
         * @list 表格数据
         * @pageNum 当前页码
         * @pageSize 每页条数
         * @total 总条数
        */
      },
      selectionList: [], // 已勾选的表格数据集合
      formData: {}, // 表单数据
      isPurchaseMultiUnit: '2', // 单计量还是多计量类别。 1为多计量，2为单计量
      actionState: false, // 是否操作按钮状态值，如果操作批量关联或者批量取消或者全部关联按钮的话，状态为true，否则为false
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
    }
  },
  methods: {
    // 是未关联
    isNotLinked () {
      return this.tabs.current === this.tabs.nameList[0];
    },
    // 是已关联
    isLinked () {
      return this.tabs.current === this.tabs.nameList[1];
    },
    /* 验证表单数据是否都为空的方法 */
    isEmptyForForm () {
      return Object.values(this.formData).every(item => !item);
    },
    /* 获取表单数据方法 */
    getFormDataFunc (source) {
      this.formData = source;
      this.handleQueryForm(); // 加载表格数据
    },
    // 查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.handleGetTableData();
    },
    // 获取查询入参 by 关联类型
    getParamsByTabsType () {
      const commonParams = {
        batchNo: this.batchNo,
        isQueryRel: this.isLinked(), // 表单查询为全部查询，为false，已关联不可输入表单条件查询，为true
        nowPage: this.pagination.pageNum,
        pageShow: this.pagination.pageSize,
      }
      if (this.isNotLinked()) {
        return {
          priceParam: { ...this.formData },
          ...commonParams
        }
      }
      if (this.isLinked()) { return commonParams; }
    },
    /* 加载表格数据事件 */
    handleGetTableData () {
      if (this.isEmptyForForm() && this.isNotLinked()) {
        return this.$message.warning('请输入搜索条件后进行关联');
      }
      this.getTableDataAction(this.getParamsByTabsType());
    },
    /* 获取表格数据action */
    getTableDataAction (data) {
      this.tableInfo.loading = true;
      ApiRequest(
        '/dataBatch/purchasePrice/getProductPage',
        'post',
        data
      ).then(res => {
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) {
          this.tableInfo.list = [];
          this.pagination.total = 0;
          return false;
        }
        let { results, totalNum } = res.retData;
        this.tableInfo.list = results;
        this.pagination.total = totalNum;
        let { pageNum, pageSize } = this.pagination;
        /* 数据备份 */
        if (this.tabs.current === this.tabs.nameList[0]) {
          this.firstStoreData = {
            list: results,
            total: totalNum,
            pageNum,
            pageSize
          }
        }
      }).catch(() => {
        this.tableInfo.loading = false;
      })
    },
    /* 切换tabs事件 */
    handleSwitchTabs () {
      this.selectionList = []; // 切换状态清空勾选数据
      this.tableInfo.list = [];
      this.pagination.total = 0;
      this.pagination.pageNum = 1;
      if (this.isLinked()) {
        this.getTableDataAction(this.getParamsByTabsType());
        this.isAllDisabled = true; // 切换到已关联表单禁用
        return false;
      }
      this.isAllDisabled = false;
      this.tableInfo.list = [];
      if (!this.isEmptyForForm()) {
        this.handleGetTableData()
      }
      /* if (this.firstStoreData.list && this.firstStoreData.list.length !== 0) {
        this.refreshTableDataFunc(this.firstStoreData);
      } else {
        this.tableInfo.list = [];
      } */
    },
    /* 刷新填充缓存的表格数据方法 */
    refreshTableDataFunc (sourceData) {
      let { list, total, pageNum, pageSize } = sourceData;
      this.tableInfo.list = list;
      this.pagination.total = total;
      this.pagination.pageNum = pageNum;
      this.pagination.pageSize = pageSize;
    },
    /* 获取勾选表格数据的uuid集合方法 */
    getUuidListFunc (key) {
      return this.selectionList.map(item => item[key || 'uuid']);
    },
    /* 全部关联事件 */
    handleAllAssociated () {
      this.formData = this.$refs.tableForm.getFormDataFunc(); // 重新获取表单内容
      if (this.isEmptyForForm()) {
        return this.$message.warning('请输入搜索条件后进行关联');
      }
      this.$confirm('确认后将会按照该搜索条件将全部数据关联，之前已关联的数据将会清空。', '全部关联', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearDataAction().then(result => {
          if (!result) { return false }
          let data = {
            batchNo: this.batchNo,
            submitType: 2,
            conditionParam: {
              ...this.formData
            }
          }
          this.formatBatchAction({
            url: '/dataBatch/purchasePrice/submitParams',
            type: 'post',
            data,
          }).then(result => {
            if (result) {
              this.$message.success('全部关联提交成功');
              this.actionState = true;
              // this.handleGetTableData(); // 重新加载表格数据
            }
          })
        })
      })
    },
    /* 清空数据action */
    clearDataAction () {
      let loading = this.$loading({ target: '.el-dialog__body' });
      return new Promise(resolve => {
        ApiRequest(
          `/dataBatch/purchasePrice/remove/${this.batchNo}`,
          'post',
          {}
        ).then(res => {
          loading.close();
          if (!isResponseSuccess(res)) {
            return false;
          }
          resolve(true);
        }).catch(() => {
          loading.close();
        })
      })
    },
    /* 批量关联事件 */
    handleBatchAssociated () {
      if (this.selectionList.length === 0) {
        return this.$message.warning('请勾选数据');
      }
      let priceUuidList = this.getUuidListFunc();
      let data = {
        batchNo: this.batchNo,
        submitType: 1,
        priceUuidList
      }
      this.formatBatchAction({
        url: '/dataBatch/purchasePrice/submitParams',
        type: 'post',
        data,
      }).then(result => {
        if (result) {
          this.$message.success('批量关联提交成功');
          this.actionState = true;
          // this.handleGetTableData(); // 重新加载表格数据
        }
      })
    },
    /* 批量取消事件 */
    handleBatchCancel () {
      if (this.selectionList.length === 0) {
        return this.$message.warning('请勾选数据');
      }
      let priceUuidList = this.getUuidListFunc();
      let data = {
        batchNo: this.batchNo,
        submitType: -1,
        priceUuidList
      }
      this.formatBatchAction({
        url: '/dataBatch/purchasePrice/submitParams',
        type: 'post',
        data,
      }).then(result => {
        if (result) {
          this.$message.success('批量取消提交成功');
          this.actionState = true;
          // this.handleGetTableData(); // 重新加载表格数据
          // this.handleSwitchTabs();
        }
      })
    },
    /* 批量操作action */
    formatBatchAction ({ url, type, data }) {
      const { rawMaterialTodoRecordNo } = this.$route.query;
      if (rawMaterialTodoRecordNo) {
        data.rawMaterialTodoRecordNo = rawMaterialTodoRecordNo;
      }
      let loading = this.$loading({ target: '.el-dialog__body' });
      return new Promise(resolve => {
        ApiRequest(url, type, data).then(res => {
          loading.close();
          if (!isResponseSuccess(res)) {
            return false;
          }
          resolve(true);
        }).catch(() => {
          loading.close();
        })
      })
    },
    /* 表格勾选事件 */
    handleSelectionChange (list) {
      this.selectionList = list;
    },
    /* 返回详情事件 */
    handleReturnDetails () {
      this.isAllDisabled = false;
      this.$emit('update:visible', false);
      this.$emit('hideDialog', this.actionState);
      this.clearInfoStatusFunc();
    },
    /* 改变页码事件 */
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 改变当前页条数大小事件 */
    handlePageSizeChange (pageSize) {
      this.pagination.pageSize = pageSize;
      if (this.tableInfo.list.length === 0) {
        return false;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 表格勾选是否禁用判断方法 */
    checkSelectableFunc ({ row }) {
      /**
       * @isRel
       * 1-已关联，checkbox置灰
       * 0-未关联，checkbox可选
      */
      return !row.hasRel;
    },
    /* 清空弹框状态 */
    clearInfoStatusFunc () {
      this.$refs.tableForm.handleResetForm();
      this.pagination = {
        pageNum: 1, // 当前页码
        pageSize: 50, // 每页条数
        total: 0
      }
      this.tableInfo.list = [];
      this.firstStoreData = {};
      this.actionState = false;
      this.tabs.current = this.tabs.nameList[0];
    }
  }
}
</script>
